package com.sp.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.sp.constant.EmployeeMessageConstant;
import com.sp.exception.BusinessException;
import com.sp.model.entity.Employee;
import com.sp.model.entity.EmployeeDetails;
import com.sp.properties.JWTProperties;
import com.sp.utils.JwtUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

import static com.sp.constant.RedisConstant.EMPLOYEE_LOGIN_USERNAME;

/**
 * JWT登录授权过滤器
 *
 * @author tong
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JWTProperties jwtProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader(jwtProperties.getTokenName());
        if (StrUtil.isNotBlank(token)) {
            String username;
            try {
                username = (String) JwtUtil.parseJWT(jwtProperties.getSecretKey(), token).get("username");
            } catch (Exception e) {
                // 设置临时身份（只是被认证，无权限）
                EmployeeDetails employeeDetails = new EmployeeDetails();
                Employee employee = new Employee();
                employee.setUsername("");
                employee.setPassword("");
                employeeDetails.setEmployee(employee);
                employeeDetails.setEmployeeRoles(new ArrayList<>());

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(employeeDetails, null, employeeDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);

                // 到拦截器中抛出异常
                // 因为该filter注入mvc中，所有请求都会通过，要忽略某些请求，可以用拦截器进行忽略
                // spring security是先认证authentication（1.通过jwt能取出授权后身份 2.未登录用户无身份），然后授权authorize（后面会根据方法所需权限去身份中取，满足则放行）
                chain.doFilter(request, response);
                return;
            }

            if (StrUtil.isNotBlank(username) /* && SecurityContextHolder.getContext().getAuthentication() == null */) {
                // 从redis中获取用户信息
                String json = stringRedisTemplate.opsForValue().get(EMPLOYEE_LOGIN_USERNAME + username);
                if (StrUtil.isBlank(json)) {
                    // redis不存在，用户已经退出登录或用户未登录
                    throw new BusinessException(EmployeeMessageConstant.EMPLOYEE_NOT_LOGIN);
                }

                EmployeeDetails employeeDetails = JSONObject.parseObject(json, EmployeeDetails.class);

                // 存入SecurityContextHolder
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(employeeDetails, null, employeeDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        //token不存在，直接放行
        chain.doFilter(request, response);
    }

}
